﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using TabsApp.form;

namespace TabsApp
{
    public partial class Desktop : Form
    {
        private int GridSize = 6;
        private bool bMoveLocation;
        private Point MouseDownPoint;
        
        public Control SelectedObject { get; private set; }
        public DesktopIconCollection SelectedObjects { get; private set; }
        public delegate void delegate_DesktopIconEventArgs(object sender, DesktopIconEventArgs e);
        public event delegate_DesktopIconEventArgs DesktopEnterEvent;
        private ContextMenuStrip ControlMenu;
        private ContextMenuStrip DesktopMenu;
        private List<DesktopIconInfo> _DataSource;
        public List<DesktopIconInfo> DataSource { get => GetDesktopSetting(); set => _DataSource = value; }

        private string strLeft= "iVBORw0KGgoAAAANSUhEUgAAADIAAAAZCAYAAABzVH1EAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAlwSFlzAAAOvAAADrwBlbxySQAAAjxJREFUWEdj+P//P8NwwMPCE6CIYIiMimHwDwxjiIlNZAgKjmCIiUtiCA6NZIhPTGUIColgSEhKA/OTUjLAdGp6NkNIWCRDWkYOmE7PzAXTmdn5DKFhUQwZWXniQLoPqHcuSD8yBslTE4dFRMMjgpoeUQR5wNLa4SkwYP77BYTuBGIGGKamB2BmUdsjWsAYmaBvaPYO5IH5i1b/LyiqRPEILTwBMpNaHjEEeUBH1+hTQHDE//Wbdv9/9e4nGCN7hFaeoIZHrIAemKyhpfcF5IGtOw7BPYDuEVp6ghKPeAMz+wwFRbWfQSFR/3ftO47hAZhHJkye/d/R2eMmKM/QEgOTVjus6iAms4cDPTBHRVXzd1hE3P9jp67g9ADMIyAa5BlQnqEltrV3fkiMRxJBRai2ruHfyOjE/1dvPibKA8ieoSV71tyl/wl5JAMYAwuNTCz/R8Uk/X/07MOg8gAscPB5pBhYIa4wt7T9HxOfOigdjxzD2Dw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qxgPUNQdyEzO1+R0ljGqEeoaSAus8CDDzToq9M9s9M6sOhWatHaIwAztrAvPO9TwwAAAABJRU5ErkJggg==";
        private string strUp = "iVBORw0KGgoAAAANSUhEUgAAABkAAAAyCAYAAACpgnCWAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAlwSFlzAAAOvAAADrwBlbxySQAABBdJREFUWEftl11sU2UYx4kXRr02JCYaL0g08YqLycr6sW7ttm5dv856ek7bs24rZy0rM5gZ8WLqYIEIKgRFYs0wmhCjLiQ6s4ASEeYCZDQwoxXFRNMYLkT2ARvd1m34+P6P6RzbaTlnQuJFl7w5O8/zf95f/897ztu364ho3f0e9x0AA7ogvBAyC2K4j+dDNXrca4aIocjDThe332KtoUZ30yExGHlEK0gzRJLaTG6PP22y2Mjt9f8Yltos9xQSDLU8VG2r2/PCju7FU2cuUNeL3QvsfjfiWkCanDS3RMsrTNZLh5PvszmJcMU94vcEIkWiD1bb63Z2dHbNf385Q7MLRLjiHnHk7wa6q5OWtvayzcbK1OHkEcXFH2NzyvWdd/vIUGFJRVrlsv8MsVhtO6TIllzq0s80NUP050SObmaJRn/4lbbEtuUqq2q6mZsHioGKOonKW5/ZZDAOvfb627TIZgEA49r4P24OHkqSYbP5fGs0tnHNEHOlrSsQjORGLv5E07P/QgCCq9ToFZIiMnNjf2lNEDmeeKqsvOKb3j37aX6Zi7wbXOFuL3O5yWAagutCoILtslbZn+cFKXc+laZbrDvLJ8//j/i5C2nyC81zzM12XRA5ltjwbLnx5K7db9Ic+7jXJ+dVIYgjDx307fHEBjWQqhN7bX2C40OzQ2dHKZtTd5F3gzx00KNOE4StxZMGo+V4T+8+ZbELuchDkIcOetShfiVolZPauoaYlxNnTg9fVN5utbVYGYMOetShvihEjnU8YTRXDe7sfUN54cZuLGiCQAd9z659ZDRbB9naPL4cdIeTRjcXdnn56RMnh5UF1eIir4Gbr8+MkIcTso4GV1QVwp6o9Wz77n+lZy9dY/vT+M1FXRC4mZz+i15lbthL/Hksvu2xPGjJicfrF1lPb5z+9qyyZdxiT83E1KKyhRRzhDx00ONv+NwIcf7wlLPRF74DEtva+ShrVX+bnKCPPhmgLwZP0fGvhum336/TFHtyCoEQRx466AdY3afHBkmOP0f1Tu+A3N6huFGc+JoEn9vLZ3ihORsMtY5zTcExj0+YPPDWe/OZqxPsk95WdYM48tBBjzr2bTkuBCNZHydkODbvEoTzi097OSHMDghCQ6Mv4PI0uWsdzpcdDZ7Msc++pBm2eam1DHHkoYMedajHPJgP8y5B1N5SMSgZqqprv0v2HaXcbXUI4shDB72uvQtiPhAy2Wrq00c++LgoBHnooNcNCeiEQF+CaF6TUrt0PcKldpXatepwUvAEWdq7NJ0g86JSu/6n7bI70h8e7VcObfj5tnIgjryN6da0QbKDgdlR70ofOJiky79cJfz6XTkQRx466HV/x4uiVO10+a74A2GKd2wnOda5aiCOPHTQ64YUKlhL/G+nu1h9He+zsAAAAABJRU5ErkJggg==";
        private string strDown = "iVBORw0KGgoAAAANSUhEUgAAABkAAAAyCAYAAACpgnCWAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAlwSFlzAAAOvAAADrwBlbxySQAABPBJREFUWEftWFlsVGUUvvGBqM/GhETjA4kkPvlQaeksXab7MvvcO/t6O9OWGkyN+FC10EAEFYIisaYQTYhRGxLFNKBEhNoAKQ3U6IhiomkMDypdoKXLtMXj+a7MnWl7Z1oxfeskJ517znfO93/nX+4/FYhIWG9TCETJt8Lcbn95faPthlP0UaJlJ8nxthUGP+LAAa9VB/UVEpfo1TJDTW1j8tDhbrr+y00auvbzCoMfceC4hkGrTl4SUfTqTRU1yQ9P9DKOaHJmpcGPOHDAPxhJZW3y2AcfU+oe0V/jqRUGP+Imxm2Q6NGGjXalV9rqS3ijXVknyEa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KCo2Dr37Xo+i5g8+n/A52n2MtutKhvjcK5A8gZz5qyq5r2ZTeUX17pa29vnvr48opwD+4hl+VrtJq91pn0qCkeQzXpaFxfrSa0e7j99XcZzwDP9quRkSN5PkMX5bPszH9972lzoWzl24Qi/u6ljk533w58tDbM0kAPv8EaPZ6vxRbzSR2eJM+v0R/WoES0hEyc/3rfzm9gQf5QvCEWNpJf/Dxn6QF8ojoptzVjFViYMvYWsxl8tbKbl9PS7Ja3Dw9WctppLgy3rauhZPD/wfEWznKsS3oy8AAAAASUVORK5CYII=";

        private Image Base64ToImage(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
            {
                ms.Write(imageBytes, 0, imageBytes.Length);
                Image image = Image.FromStream(ms, true);
                return image;
            }
        }

        public Desktop()
        {
            InitializeComponent();
            this.BackColor = Color.FromArgb(255,51,153,255);
            this.WindowState = FormWindowState.Maximized;
            this.KeyPreview = true;
            AddMenu();

        }

        private void AddMenu()
        {
            components = new Container();
            this.DesktopMenu = new ContextMenuStrip(components);
            this.ControlMenu = new ContextMenuStrip(components);
            string strSplit = "---";
            Dictionary<string, string> menuList = new Dictionary<string, string>
            {
                { "m_open", "打开(&O)" },
                { "m_split1", strSplit },
                { "m_del" , "删除(&D)" },
                { "m_rename", "重命名(&M)" },
                { "m_split2", strSplit },
                { "m_property", "属性(&R)" }
            };

            foreach (KeyValuePair<string, string> item in menuList)
            { 
                if (item.Value.Equals(strSplit)) {
                    ControlMenu.Items.Add(new ToolStripSeparator());
                }
                else
                {
                    ToolStripMenuItem m_option = new ToolStripMenuItem();
                    m_option.Name = item.Key;
                    m_option.Text = item.Value;
                    m_option.Click += optionMenu_Click;
                    ControlMenu.Items.Add(m_option);
                } 
            }
            ToolStripMenuItem md_newopt = new ToolStripMenuItem();
            md_newopt.Name = "m_new";
            md_newopt.Text = "新建(&N)";

            Dictionary<string, string> menuLst = new Dictionary<string, string>
            {
                { "m_left", "左箭头" },
                { "m_right", "右箭头" },
                { "m_up" , "上箭头" },
                { "m_down", "下箭头" }
            };
            foreach (KeyValuePair<string, string> item in menuLst)
            {
                ToolStripMenuItem md_newoptItem = new ToolStripMenuItem();
                md_newoptItem.Name = item.Key;
                md_newoptItem.Text = item.Value;
                md_newoptItem.Click += optionMenu_Click;
                md_newopt.DropDownItems.Add(md_newoptItem);
            }   
            ToolStripMenuItem md_resopt = new ToolStripMenuItem();
            md_resopt.Name = "m_res";
            md_resopt.Text = "刷新(&E)";
            md_resopt.Click += optionMenu_Click;

            DesktopMenuAdd(new ToolStripItem[] { md_newopt, new ToolStripSeparator(), md_resopt });
        }

        /// <summary>
        /// 添加桌面菜单
        /// </summary>
        /// <param name="menus"></param>
        public void DesktopMenuAdd(ToolStripItem[] menus)
        {
            DesktopMenu.Items.AddRange(menus);
        }

        /// <summary>
        /// 添加桌面菜单
        /// </summary>
        /// <param name="menu"></param>
        public void DesktopMenuAdd(ToolStripItem menu)
        {
            DesktopMenu.Items.Add(menu);
        }

        private void optionMenu_Click(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem) { }
            switch ((sender as ToolStripMenuItem).Name)
            {
                case "m_open":
                    var e1 = new DesktopIconEventArgs();
                    e1.cmd = (ControlMenu.Tag as DesktopIcon).Tag.ToString();
                    DesktopEnterEvent(SelectedObject, e1);
                    break;
                case "m_del":
                    Control control = ControlMenu.Tag as Control;
                    RemoveControl(control);
                    break;
                case "m_rename":
                    DesktopIcon con = (DesktopIcon)ControlMenu.Tag;
                    con.ShowRenameBox(con.Caption);
                    break;
                case "m_property":
                    control = ControlMenu.Tag as DesktopIcon;
                    ShowProperty(control);
                    break;
                case "m_res":
                    var tmp = this.DataSource;
                    Controls.Clear();
                    DataSource = tmp;
                    AddIcon();
                    break;
                case "m_left":
                    AddArrow(1, DesktopMenu.Left, DesktopMenu.Top);
                    break;
                case "m_right":
                    AddArrow(2, DesktopMenu.Left, DesktopMenu.Top);
                    break;
                case "m_up":
                    AddArrow(3, DesktopMenu.Left, DesktopMenu.Top);
                    break;
                case "m_down":
                    AddArrow(4, DesktopMenu.Left, DesktopMenu.Top);
                    break;
            }
        }

        private void ShowProperty(Control control)
        {
            string AppName = string.Empty;
            string AppDec = string.Empty;
            if (control is DesktopIcon)
            {
                AppName = (control as DesktopIcon).Caption;
                AppDec = (control as DesktopIcon).Tag.ToString();
            }
            var str = string.Format("类型:\t快捷方式\t\r标题:\t{0}\t\r目标:\t{1}\t\r",AppName,AppDec);
            var result = MessageBox.Show(str, "属性", MessageBoxButtons.OKCancel, MessageBoxIcon.None);
            if (result == DialogResult.OK)
            {
                
            }
        }

        private void Desktop_Load(object sender, EventArgs e)
        {
            SelectedObjects = new DesktopIconCollection();
            Thread InvenThread = new Thread(AddIcon_Invoke);
            InvenThread.Start();
        }
        private delegate void MyInvoke();

        private void AddIcon_Invoke()
        {
            var myinvoke = new MyInvoke(AddIcon);
            Invoke(myinvoke);
        }

        private void AddIcon()
        {
            if (_DataSource == null) { return; }
            List<DesktopIconInfo> list = this._DataSource;
            foreach (var item in list)
            {
                switch (item.type)
                {
                    case 0:
                        var con = new DesktopIcon();
                        con.Image = this.Icon.ToBitmap();
                        con.BackColor = Color.Transparent;
                        con.CaptionForeColor = Color.White;
                        con.Tag = item.cmd;
                        con.Caption = item.title;
                        con.Left = item.left;
                        con.Top = item.top;
                        this.Controls.Add(con);
                        break;
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        this.AddArrow(int.Parse(item.cmd), item.left, item.top);
                        break;
                    default:
                        break;
                } 
            }     
        }

        private List<DesktopIconInfo> GetDesktopSetting()
        {
            this.HorizontalScroll.Value = 0;
            this.VerticalScroll.Value = 0;
            List<DesktopIconInfo> list = new List<DesktopIconInfo>();
            foreach (Control item in Controls)
            {
                DesktopIconInfo info = new DesktopIconInfo();
                if (item is DesktopIcon)
                {
                    info.cmd = item.Tag.ToString();
                    info.title = (item as DesktopIcon).Caption;
                    info.type = 0;
                }
                else
                {
                    info.cmd = item.Tag != null ? item.Tag.ToString() : "0";
                    info.type = item.Tag != null ? int.Parse(item.Tag.ToString()) : 0;
                }
                info.left = item.Left;
                info.top = item.Top;
                list.Add(info);
            }
            return list;
        }

        public void AddDesktopIcon(string title, string cmd)
        {
            AddDesktopIcon(title, cmd, null);
        }

        public void AddDesktopIcon(string title, string cmd, Bitmap bitmap)
        {
            DesktopIcon con = new DesktopIcon();
            con.Tag = cmd;
            con.Caption = title;
            con.BackColor = Color.Transparent;
            con.CaptionForeColor = Color.White;
            if (bitmap == null) { con.Image = this.Icon.ToBitmap(); } else { con.Image = bitmap; }
            for (int i = 0; i < (this.Width - 96); i++)
            {
                for (int j = 0; j < (this.Height - 96); j++)
                {
                    Application.DoEvents();
                    Rectangle rect = new Rectangle(i, j, con.Width, con.Height);
                    if (!ExistControl(rect))
                    {
                        con.Left = i;
                        con.Top = j;
                        this.Controls.Add(con);
                        return;
                    }
                }
            }
        }

        private bool ExistControl(Rectangle rect)
        {
            foreach (Control con in this.Controls)
            {
                Point[] ps = new Point[4];
                ps[0] = new Point(con.Left, con.Top);
                ps[1] = new Point(con.Left + con.Width, con.Top);
                ps[2] = new Point(con.Left, con.Top + con.Height);
                ps[3] = new Point(con.Left + con.Width, con.Top + con.Height);
                foreach (var p in ps)
                {
                    if(p.X >= rect.X && p.Y >= rect.Y && p.X <= rect.X + rect.Width && p.Y <= rect.Y + rect.Height){
                        return true;
                    }
                }
            }
            return false;
        }

        private void AddArrow(int ArrowIndex, int left, int top)
        {
            PictureBox pic = new PictureBox
            {
                SizeMode = PictureBoxSizeMode.CenterImage,
                Width = 50,
                Height = 50,
                BackColor = Color.Transparent,
                Left = left,
                Top = top,
                Tag = ArrowIndex
            };
            switch (ArrowIndex)
            {
                case 1:
                    pic.Image = Base64ToImage(strLeft);
                    break;
                case 2:
                    pic.Image = Base64ToImage(strRight);
                    break;
                case 3:
                    pic.Image = Base64ToImage(strUp);
                    break;
                case 4:
                    pic.Image = Base64ToImage(strDown);
                    break;
                default:
                    break;
            }
            this.Controls.Add(pic);
        }

        private void Desktop_ControlAdded(object sender, ControlEventArgs e)
        {
            e.Control.MouseDown += con_MouseDown;
            e.Control.MouseMove += con_MouseMove;
            e.Control.MouseUp += con_MouseUp;
            e.Control.MouseClick += con_MouseClick;
            e.Control.Click += con_Click;
            e.Control.DoubleClick += con_DoubleClick;
            e.Control.GotFocus += con_GotFocus;
            e.Control.KeyDown += con_KeyDown;
        }

        private void RemoveControl(Control control)
        {
            if (control == null) { return; }
            if (SelectedObjects.Count > 1)
            {
                var result1 = MessageBox.Show("确定要永久这些删除此快捷方式?\t\r\t\r删除此快捷方式不会彻底删除程序。只会删除指向该程序的图标。\t\r该操作将删除" + SelectedObjects.Count +"个选中快捷方式项目", "删除快捷方式", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result1 == DialogResult.Yes)
                {
                    foreach (var item in SelectedObjects)
                    {
                        Controls.Remove(item);
                    }
                }
            }
            else {
                if (control is PictureBox) { Controls.Remove(control as PictureBox); return; }
                string AppName = string.Empty;
                string AppDec = string.Empty;
                if (control is DesktopIcon)
                {
                    AppName = "应用名：\t" + (control as DesktopIcon).Caption;
                    AppDec = "指向命令：\t" + (control as DesktopIcon).Tag.ToString();
                }
                var result = MessageBox.Show("确定要永久删除此快捷方式?\t\r\t\r删除此快捷方式不会彻底删除程序。只会删除指向该程序的图标。\t\r" + AppName + "\t\r\t\r" + AppDec, "删除快捷方式", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.Yes)
                {
                    Controls.Remove(control);
                }
            }
            SelectedNo();
        }

        private void con_KeyDown(object sender, KeyEventArgs e)
        {
            Control con = sender as Control;
            if (e.KeyCode == Keys.Enter)
            {
                var e1 = new DesktopIconEventArgs();
                e1.cmd = con.Tag.ToString();
                DesktopEnterEvent(sender, e1);
            }else if (e.KeyCode==Keys.Delete)
            {
                RemoveControl(sender as Control);
            }else if (e.Control && e.KeyCode== Keys.A)
            {
                foreach (Control item in Controls)
                {
                    DrawControl(item);
                    SelectedObjects.Add(item);
                }
            }else if (e.KeyCode==Keys.Apps)
            {
               
                this.Refresh();
                ControlMenu.Tag = sender;
                this.ControlMenu.Show(con, con.Left+con.Width, con.Top);
            }
        }

        private void con_GotFocus(object sender, EventArgs e)
        {
            foreach (Control item in Controls)
            {
                item.BackColor = Color.Transparent;
                if (item is DesktopIcon)
                {
                    (item as DesktopIcon).CaptionForeColor = Color.White;
                }
            }
            if (sender is DesktopIcon)
            {
                var con = sender as DesktopIcon;
                con.BackColor = Color.FromArgb(50, 255, 255, 255);
                con.CaptionForeColor = Color.Black;
                SelectedObject = con;
            }
        }

        private void con_Click(object sender, EventArgs e)
        {
            if (sender.GetType() == typeof(DesktopIcon))
            {
                SelectedObject = sender as Control;
                SelectedObject.Focus();  
            }
        }

        private void con_DoubleClick(object sender, EventArgs e)
        {
            if (sender.GetType() == typeof(DesktopIcon))
            {
                Control con = sender as Control;
                var e1 = new DesktopIconEventArgs();
                e1.cmd = con.Tag.ToString();
                DesktopEnterEvent(sender, e1);
            }       
        }

        private void con_MouseClick(object sender, MouseEventArgs e)
        {
            
            if (e.Button != MouseButtons.Right)
            {
                this.Refresh();
                SelectedObject = sender as Control;
                SelectedObject.Focus();
                SelectedObjects.Clear();
                SelectedObjects.Add(SelectedObject);
                return;
            }
            ControlMenu.Tag = sender;
            if(sender is DesktopIcon)
            {
                foreach (ToolStripItem item in ControlMenu.Items)
                { 
                     item.Enabled = true;
                }
                this.ControlMenu.Show(sender as Control, e.X, e.Y);
            }
            else
            {
                foreach (ToolStripItem item in ControlMenu.Items)
                {
                    if (!item.Name.Equals("m_del")) {
                        item.Enabled = false;
                    }
                }
                this.ControlMenu.Show(sender as Control, e.X, e.Y);
            }
            SignChooseControls();
        }

        private void con_MouseUp(object sender, MouseEventArgs e)
        {
            if (bMoveLocation)
            {
                bMoveLocation = false;
            }
        }

        private void con_MouseMove(object sender, MouseEventArgs e)
        {
            if (bMoveLocation == false){
                return;
            }
            if (SelectedObjects.Count > 1)
            {
                foreach (Control item in SelectedObjects)
                {
                    item.Left += e.X - MouseDownPoint.X;
                    item.Top += e.Y - MouseDownPoint.Y;
                }
            }
            else
            {
                var con = sender as Control;
                con.Left += e.X - MouseDownPoint.X;
                con.Top += e.Y - MouseDownPoint.Y;
            }
            SignChooseControls();
        }

        private void SignChooseControls()
        {
            foreach (Control item in Controls)
            {
                item.Refresh();
            }
            foreach (Control item in SelectedObjects)
            {
                DrawControl(item);
            }
        }

        private void SelectedNo()
        {
            SelectedObject = null;
            SelectedObjects.Clear();
            SignChooseControls();
        }

        private void DrawControl(Control item)
        {
            if(item== SelectedObject)
            {
                DrawControl(item, true);
            }
            else
            {
                DrawControl(item, false);
            }
        }

        private void DrawControl(Control item, bool v)
        {
            Point[] ps=new Point[8];
            ps[0] = new Point(0, 0);
            ps[1] = new Point((item.Width - GridSize) / 2, 0);
            ps[2] = new Point(item.Width - GridSize, 0);
            ps[3] = new Point(0, (item.Height - GridSize) / 2);
            ps[4] = new Point(item.Width - GridSize, (item.Height - GridSize) / 2);
            ps[5] = new Point(0, item.Height - GridSize);
            ps[6] = new Point((item.Width - GridSize) / 2, item.Height - GridSize);
            ps[7] = new Point(item.Width - GridSize, item.Height - GridSize);
            DrawControl(item, ps, v);
        }

        private void DrawControl(Control item, Point[] ps, bool v)
        {
            item.Refresh();
            Graphics draw = item.CreateGraphics();
            foreach (var p in ps)
            {
                if (v)
                {
                    draw.FillRectangle(Brushes.White, p.X, p.Y, GridSize - 1, GridSize - 1);
                }
                else
                {
                    draw.DrawRectangle(Pens.White, p.X, p.Y, GridSize - 1, GridSize -1);
                }
            }
            var pen = new Pen(Brushes.White, 1);
            pen.DashStyle = DashStyle.Custom;
            pen.DashPattern = new float[]{ 1, 1};
            var rect= new Rectangle(GridSize / 2+2, GridSize / 2+2, item.Width - GridSize-5, item.Height - GridSize-5);
            draw.DrawRectangle(pen, rect);
        }

        private void con_MouseDown(object sender, MouseEventArgs e)
        {
            Control con;
            foreach (Control item in Controls)
            {
                con = item;
                con.BackColor = Color.Transparent;
                if (con.GetType() == typeof(DesktopIcon))
                {
                    (con as DesktopIcon).CaptionForeColor = Color.White;
                }
            }
            con = sender as Control;
            con.BackColor = Color.FromArgb(50, 255, 255, 255);
            if (con.GetType() == typeof(DesktopIcon))
            {
                (con as DesktopIcon).CaptionForeColor = Color.Black;
            }
            if (e.Button == MouseButtons.Left)
            {
                bMoveLocation = true;
                MouseDownPoint = new Point(e.X, e.Y);
            }
            con.BringToFront();
        }

        private void Desktop_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.Refresh();
                DesktopMenu.Show(sender as Control,e.X,e.Y);
                return;
            }

        }

        private void Desktop_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) {
                MouseDownPoint.X = e.X;
                MouseDownPoint.Y = e.Y;
            }
        }

        private void Desktop_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) {
                Graphics g = this.CreateGraphics();
                g.Clear(BackColor);
                int x = MouseDownPoint.X < e.X ? MouseDownPoint.X : e.X;
                int y =MouseDownPoint.Y < e.Y ? MouseDownPoint.Y : e.Y;
                int Width = Math.Abs(MouseDownPoint.X - e.X);
                int Height = Math.Abs(MouseDownPoint.Y - e.Y);
                var rect = new Rectangle(x, y, Width, Height);
                var pen = new Pen(Color.White, 1);
                pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
                pen.DashPattern = new float[] { 1, 1 };
                g.DrawRectangle(pen, rect);
            }
        }

        private void Desktop_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int x = MouseDownPoint.X < e.X ? MouseDownPoint.X : e.X;
                int y = MouseDownPoint.Y < e.Y ? MouseDownPoint.Y : e.Y;
                int Width = Math.Abs(MouseDownPoint.X - e.X);
                int Height = Math.Abs(MouseDownPoint.Y - e.Y);
                var rect = new Rectangle(x, y, Width, Height);
                SelectedObjects = getControls_byRectangle((sender as Control), rect);
                if (SelectedObjects.Exits())
                {
                    SelectedObject = SelectedObjects[0];
                    SelectedObject.Focus();
                }
                else
                {
                    SelectedObject = null;
                }
                Refresh();
                SignChooseControls();
            }
        }

        private DesktopIconCollection getControls_byRectangle(Control control, Rectangle rect)
        {
            var cons = new DesktopIconCollection();
            foreach (Control item in control.Controls)
            {
                if (isChoosed(item, rect) && item.Visible)
                {
                    cons.Add(item);
                }
            }
            return cons;
        }

        private bool isChoosed(Control con, Rectangle rect)
        {
            var rect2 = new Rectangle(con.Left, con.Top, con.Width, con.Height);
            if (isChoosed(rect, rect2)) {
                return true;
            }
            if (isChoosed(rect2, rect)) {
                return true;
            }
        return false;
        }

        private bool isChoosed(Rectangle rect1, Rectangle rect2)
        {
            var P1 = new Point(rect1.X, rect1.Y);
            var P2 =new Point(rect1.X + rect1.Width, rect1.Y);
            var P3 =new Point(rect1.X, rect1.Y + rect1.Height);
            var P4 =new Point(rect1.X + rect1.Width, rect1.Y + rect1.Height);
            if (isChoosed(P1, rect2)) {
                return true;
            }
            if (isChoosed(P2, rect2)) {
                return true;
            }
            if(isChoosed(P3, rect2))
            {
                return true;
            }
            if( isChoosed(P4, rect2))
            {
                return true;
            }
            return false;
        }

        private bool isChoosed(Point P, Rectangle rect)
        {
            if( P.X > rect.X && P.X < rect.X + rect.Width && P.Y > rect.Y && P.Y < rect.Y + rect.Height) {
                return true;
            }
            return false;
        }

        private void Desktop_Click(object sender, EventArgs e)
        {
            
            Control con;
            foreach (Control item in Controls)
            {
                con = item;
                con.BackColor = Color.Transparent;
                if (con is DesktopIcon)
                {
                    (con as DesktopIcon).CaptionForeColor = Color.White;
                }
            }
            SelectedNo();
            this.Focus();
        }

        private void Desktop_FormClosing(object sender, FormClosingEventArgs e)
        {
            
        }
    }

    public class DesktopIconCollection: System.Collections.ObjectModel.Collection<Control>
    {
        public bool Exits()
        {
            if (Count == 0) {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

    public class DesktopIconEventArgs
    {
        public string cmd;
    }

    public class DesktopIconInfo
    {
        public int type { get; set; }
        public int left { get; set; }
        public int top { get; set; }
        public string title { get; set; }
        public string cmd { get; set; }
    }

}